﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Common.Dto;
using Common.Util;
using Demo03.Config.Properties;
using Microsoft.AspNetCore.Mvc;

namespace Demo03.Controller;

/// <summary>
/// Token接口
/// </summary>
[ApiController]
[Route("token")]
public class TokenController
{
    private readonly ProjectProperties _projectProperties;

    /// <summary>
    /// 构造器
    /// </summary>
    /// <param name="projectProperties"></param>
    public TokenController(ProjectProperties projectProperties)
    {
        _projectProperties = projectProperties;
    }

    /// <summary>
    /// 生成token
    /// </summary>
    /// <param name="payload"></param>
    /// <returns></returns>
    [HttpPost("encode")]
    [Consumes("application/json")]
    public Result<string> Encode([Required] [FromBody] List<KeyValuePair<string, object>> claims)
    {
        var payload = new Dictionary<string, object>(claims);
        var token = TokenUtil.EncodeWithHs256(_projectProperties.JwtKey, DateTimeOffset.Now.AddHours(1), payload);
        return Result.Success(token);
    }
}